﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Sealight.API.Framework;
using Sealight.Data;
using Sealight.API.Ioc;
using Sealight.Core.Domain;
using Sealight.Core.DataAdapter;

namespace Sealight.CoreAPI
{
  public  class NewsService: INewsService
    {
        #region INewsService Members

        public news AddOrUpdate(news data)
        {
            if (data == null)
                throw new ArgumentNullException("News data is Null.");
            //persists
            #region start_unit_of_work
            IUnitOfWork uow = null;
            if (!UnitOfWork.IsStarted)
                uow = UnitOfWork.Start();
            else uow = UnitOfWork.Current;
            #endregion
            bool commitTrans = false;
            if (!uow.IsInActiveTransaction)
            {
                //if not in active transaction
                //then begin transaction and commit it later
                uow.BeginTransaction(); //start transaction
                commitTrans = true;
            }

            try
            {
                INewsDataRepository repo = IocContainer.Container().Resolve<INewsDataRepository>();
                ITopicDataRepository repoLanguage = IocContainer.Container().Resolve<ITopicDataRepository>();

                NewsEntity entity = repo.GetById(data.id);

                if (entity == null)
                    entity = new NewsEntity();

                entity.Title = data.title;
                entity.Description = data.description;
                entity.Detail = data.detail;                
                entity.ImageURL = data.image_url;
                entity.Keyword = data.keyword;
                entity.NumberView = data.number_view;
                entity.CreatedDate = data.created_date;
                entity.UpdatedDate = data.updated_date;
                entity.PublishedDate = data.published_date;

                if (data.language != null)
                {
                    entity.Language = repoLanguage.GetLanguageById(data.language.id);
                }
                entity.IsActive = data.is_active;

                if (data.category != null)
                {
                    entity.NewsCategory = repo.GetCategory(data.category.id);
                }

                if (data.source != null)
                {
                    entity.NewsSource = repo.GetSourceById(data.source.id);
                }

                repo.SaveOrUpdate(entity);

                if (commitTrans)
                    uow.TransactionalFlush();

                data = entity.ToDataAdapter();
               
            }
            catch (Exception ex)
            {
                //log for net
                throw new Exception("Error saving user data. ErrMsg: " + ex.Message, ex);
            }

            return data;
        }

        public news GetById(Guid id)
        {
            if (id == Guid.Empty)
                throw new ArgumentNullException("News ID cannot be NULL.");

            NewsEntity data = null;
            try
            {
                #region start_unit_of_work
                IUnitOfWork uow = null;
                if (!UnitOfWork.IsStarted)
                    uow = UnitOfWork.Start();
                else uow = UnitOfWork.Current;
                #endregion
                INewsDataRepository repo = IocContainer.Container().Resolve<INewsDataRepository>();
                data = repo.GetById(id);
            }
            catch (Exception ex)
            {
                throw new Exception("Get Service Error::" + ex.Message, ex);
            }

            if (data != null)
                return data.ToDataAdapter();

            return null;
        }

        public void Delete(news data)
        {
            //persists
            #region start_unit_of_work
            IUnitOfWork uow = null;
            if (!UnitOfWork.IsStarted)
                uow = UnitOfWork.Start();
            else uow = UnitOfWork.Current;
            #endregion
            bool commitTrans = false;
            if (!uow.IsInActiveTransaction)
            {
                //if not in active transaction
                //then begin transaction and commit it later
                uow.BeginTransaction(); //start transaction
                commitTrans = true;
            }

            try
            {
                INewsDataRepository repo = IocContainer.Container().Resolve<INewsDataRepository>();               
                NewsEntity entity = repo.GetById(data.id);

                repo.Delete(entity);

                if (commitTrans)
                    uow.TransactionalFlush();
            }
            catch (Exception ex)
            {
                //log for net
                throw new Exception("Error saving user data. ErrMsg: " + ex.Message, ex);
            }
        }

        public IList<news> GetAllNews()
        {
            IList<NewsEntity> listData = null;
            try
            {
                #region start_unit_of_work
                IUnitOfWork uow = null;
                if (!UnitOfWork.IsStarted)
                    uow = UnitOfWork.Start();
                else uow = UnitOfWork.Current;
                #endregion
                INewsDataRepository repo = IocContainer.Container().Resolve<INewsDataRepository>();
                listData = repo.GetAll();
            }
            catch (Exception ex)
            {
                throw new Exception("Error get service data. ErrMsg: " + ex.Message, ex);
            }
            IList<news> dataAdapter = null;
            if (listData != null)
            {
                dataAdapter = (from c in listData orderby c.UpdatedDate descending select c.ToDataAdapter()).ToList();
            }
            return dataAdapter;
        }

        public IList<news_source> GetAllSource()
        {
            IList<NewsSourceEntity> listData = null;
            try
            {
                #region start_unit_of_work
                IUnitOfWork uow = null;
                if (!UnitOfWork.IsStarted)
                    uow = UnitOfWork.Start();
                else uow = UnitOfWork.Current;
                #endregion
                INewsDataRepository repo = IocContainer.Container().Resolve<INewsDataRepository>();
                listData = repo.GetAllSource();
            }
            catch (Exception ex)
            {
                throw new Exception("Error get News Source data. ErrMsg: " + ex.Message, ex);
            }
            IList<news_source> dataAdapter = null;
            if (listData != null)
            {
                dataAdapter = new List<news_source>();
                foreach (NewsSourceEntity entity in listData)
                {
                    dataAdapter.Add(entity.ToDataAdapter());
                }
            }
            return dataAdapter;
        }

        #endregion
    }
}
